﻿namespace Hidistro.UI.SaleSystem.CodeBehind
{
    using Hidistro.Core;
    using Hidistro.Core.Configuration;
    using Hidistro.Entities.Sales;
    using Hidistro.Membership.Context;
    using Hidistro.Membership.Core;
    using Hidistro.Membership.Core.Enums;
    using Hidistro.Messages;
    using Hidistro.SaleSystem.Member;
    using Hidistro.SaleSystem.Shopping;
    using Hidistro.UI.Common.Controls;
    using Hishop.Components.Validation;
    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.HtmlControls;
    using wnxd.javascript;
    using wnxd.Web;
    using System.Text.RegularExpressions;

    public class Register_new : HtmlTemplatedWebControl
    {
        private string verifyCodeKey = "VerifyCode";
        private Web wnxd_web;

        protected override void AttachChildControls()
        {
            PageTitle.AddSiteNameTitle("会员注册");
            this.wnxd_web = (Web)this.FindControl("wnxd_web");
            this.wnxd_web.AddScript("PML = " + Membership.Provider.MinRequiredPasswordLength + ";");
        }
        protected void Register(Page Page)
        {
            bool error = false;
            if (Page.Request.Form["register$ctl04"] != "on")
            {
                ((Web)this.FindControl("wnxd_web")).AddScript("alert(\"您必须先阅读并同意注册协议\");");
                error = true;
            }
            Control form = this.FindControl("wnxd");
            string email = (email = Page.Request.Form["register$ctl01"]) == null ? "" : email.Trim();
            if (email.Length < 2 || email.Length > 40)
            {
                HtmlGenericControl div = (HtmlGenericControl)form.FindControl("zhmsg");
                div.InnerText = "账号须在2-40字符之间";
                div.Visible = true;
                error = true;
            }
            if (string.Compare(email.ToLower(CultureInfo.InvariantCulture), "anonymous", false, CultureInfo.InvariantCulture) == 0)
            {
                HtmlGenericControl div = (HtmlGenericControl)form.FindControl("zhmsg");
                div.InnerText = "已经存在相同的用户名";
                div.Visible = true;
                error = true;
            }
            else if (!new Regex(@"^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$").IsMatch(email))
            {
                HtmlGenericControl div = (HtmlGenericControl)form.FindControl("zhmsg");
                div.InnerText = "请输入正确的邮箱";
                div.Visible = true;
                error = true;
            }
            string password = (password = Page.Request.Form["register$ctl02"]) == null ? "" : password.Trim();
            if (password.Length < Membership.Provider.MinRequiredPasswordLength || password.Length > HiConfiguration.GetConfig().PasswordMaxLength)
            {
                HtmlGenericControl div = (HtmlGenericControl)form.FindControl("mmmsg");
                div.InnerText = string.Format("密码的长度只能在{0}和{1}个字符之间", Membership.Provider.MinRequiredPasswordLength, HiConfiguration.GetConfig().PasswordMaxLength);
                div.Visible = true;
                error = true;
            }
            string password2 = (password2 = Page.Request.Form["register$ctl03"]) == null ? "" : password2.Trim();
            if (password2 != password)
            {
                HtmlGenericControl div = (HtmlGenericControl)form.FindControl("mm2msg");
                div.InnerText = "两次输入的密码不相同";
                div.Visible = true;
                error = true;
            }
            string verifycode = (verifycode = Page.Request.Form["verifycode"]) == null ? "" : verifycode.Trim();
            if (!this.CheckVerifyCode(verifycode))
            {
                HtmlGenericControl div = (HtmlGenericControl)form.FindControl("vcmsg");
                div.InnerText = "验证码输入错误";
                div.Visible = true;
                error = true;
            }
            if (!error)
            {
                Member member = null;
                member = new Member(UserRole.Member);
                if (HiContext.Current.ReferralUserId > 0)
                {
                    member.ReferralUserId = new int?(HiContext.Current.ReferralUserId);
                }
                member.GradeId = MemberProcessor.GetDefaultMemberGrade();
                member.Username = Globals.HtmlEncode(email);
                member.Email = email;
                member.Password = password;
                member.PasswordFormat = MembershipPasswordFormat.Hashed;
                member.TradePasswordFormat = MembershipPasswordFormat.Hashed;
                member.TradePassword = password;
                member.IsApproved = true;
                member.RealName = string.Empty;
                member.Address = string.Empty;
                switch (MemberProcessor.CreateMember(member))
                {
                    case CreateUserStatus.UnknownFailure:
                        {
                            ((Web)this.FindControl("wnxd_web")).AddScript("alert(\"未知错误\");");
                            break;
                        }
                    case CreateUserStatus.Created:
                        {
                            Messenger.UserRegister(member, password);
                            member.OnRegister(new UserEventArgs(member.Username, password, null));
                            IUser user = Users.GetUser(0, member.Username, false, true);
                            ShoppingCartInfo cookieShoppingCart = ShoppingCartProcessor.GetCookieShoppingCart();
                            HiContext.Current.User = user;
                            if (cookieShoppingCart != null)
                            {
                                ShoppingCartProcessor.ConvertShoppingCartToDataBase(cookieShoppingCart);
                                ShoppingCartProcessor.ClearCookieShoppingCart();
                            }
                            HttpCookie authCookie = FormsAuthentication.GetAuthCookie(member.Username, false);
                            user.GetUserCookie().WriteCookie(authCookie, 30, false);
                            Page.Response.Redirect(Globals.GetSiteUrls().UrlData.FormatUrl("user_UserCenter"));
                            break;
                        }
                    case CreateUserStatus.DuplicateUsername:
                        {
                            HtmlGenericControl div = (HtmlGenericControl)form.FindControl("zhmsg");
                            div.InnerText = "电子邮件地址已经存在";
                            div.Visible = true;
                            break;
                        }
                    case CreateUserStatus.DuplicateEmailAddress:
                        {
                            HtmlGenericControl div = (HtmlGenericControl)form.FindControl("zhmsg");
                            div.InnerText = "电子邮件地址已经存在";
                            div.Visible = true;
                            break;
                        }
                    case CreateUserStatus.DisallowedUsername:
                        {
                            HtmlGenericControl div = (HtmlGenericControl)form.FindControl("zhmsg");
                            div.InnerText = "用户名禁止注册";
                            div.Visible = true;
                            break;
                        }
                    case CreateUserStatus.InvalidPassword:
                        {
                            HtmlGenericControl div = (HtmlGenericControl)form.FindControl("mmmsg");
                            div.InnerText = "无效的密码";
                            div.Visible = true;
                            break;
                        }
                }
            }
        }

        private bool CheckVerifyCode(string verifyCode)
        {
            if (HttpContext.Current.Request.Cookies[this.verifyCodeKey] == null)
            {
                return false;
            }
            return (string.Compare(HiCryptographer.Decrypt(HttpContext.Current.Request.Cookies[this.verifyCodeKey].Value), verifyCode, true, CultureInfo.InvariantCulture) == 0);
        }

        protected override void OnInit(EventArgs e)
        {
            this.Page.Response.Redirect("http://account.x-juse.com/Register.aspx?sdomain=" + HttpUtility.UrlEncode("http://" + this.Page.Request.Url.Authority));
            if (this.SkinName == null)
            {
                this.SkinName = "Skin-Register_new.html";
            }
            base.OnInit(e);
        }

        private bool ValidationMember(Member member)
        {
            ValidationResults results = Hishop.Components.Validation.Validation.Validate<Member>(member, new string[] { "ValMember" });
            string msg = string.Empty;
            if (!results.IsValid)
            {
                foreach (ValidationResult result in (IEnumerable<ValidationResult>)results)
                {
                    msg = msg + Formatter.FormatErrorMessage(result.Message);
                }
                this.ShowMessage(msg, false);
            }
            return results.IsValid;
        }



        public string GetPYString(string str)
        {
            string tempStr = "";
            foreach (char c in str)
            {
                if ((int)c >= 33 && (int)c <= 126)
                {//字母和符号原样保留
                    tempStr += c.ToString();
                }
                else
                {//累加拼音声母
                    tempStr += GetPYChar(c.ToString());
                }
            }
            return tempStr;
        }

        public string GetPYChar(string c)
        {
            byte[] array = new byte[2];
            array = System.Text.Encoding.Default.GetBytes(c);
            int i = (short)(array[0] - '\0') * 256 + ((short)(array[1] - '\0'));

            if (i < 0xB0A1) return "*";
            if (i < 0xB0C5) return "a";
            if (i < 0xB2C1) return "b";
            if (i < 0xB4EE) return "c";
            if (i < 0xB6EA) return "d";
            if (i < 0xB7A2) return "e";
            if (i < 0xB8C1) return "f";
            if (i < 0xB9FE) return "g";
            if (i < 0xBBF7) return "h";
            if (i < 0xBFA6) return "g";
            if (i < 0xC0AC) return "k";
            if (i < 0xC2E8) return "l";
            if (i < 0xC4C3) return "m";
            if (i < 0xC5B6) return "n";
            if (i < 0xC5BE) return "o";
            if (i < 0xC6DA) return "p";
            if (i < 0xC8BB) return "q";
            if (i < 0xC8F6) return "r";
            if (i < 0xCBFA) return "s";
            if (i < 0xCDDA) return "t";
            if (i < 0xCEF4) return "w";
            if (i < 0xD1B9) return "x";
            if (i < 0xD4D1) return "y";
            if (i < 0xD7FA) return "z";

            return "*";
        }
    }
}

